const Koa = require('koa');
const server = new Koa();
const session = require('koa-session');
const fs = require('fs');
const path = require('path');
const body = require('koa-better-body');
const db = require('./libs/database.js');
const ejs = require('koa-ejs');
const Router = require('koa-router');
const static = require('./router/static.js');   // 自定义的文件类型静态资源托管以及缓存时间
const config = require('./config');

server.listen(8080, () => {
    console.log(`server is started...`);
})
/////////////////////////////// 中间件 ///////////////////////////////
// session
server.keys = fs.readFileSync(path.resolve(__dirname, '.keys')).toString().split('\n');
let sessionConfig = {
    maxAge: 1000 * 60 * 20,
    renew: true
}
server.use(session(sessionConfig, server));
// post请求
server.use(body({
    uploadDir: path.resolve(__dirname, './static/upload')
}));
// 数据库连接
server.context.db = db;
server.context.config = config;
// ejs 渲染
ejs(server, {
    root: path.join(__dirname, 'template'),
    layout: false,
    viewExt: 'ejs',
    cache: false,
    debug: false
});
// 路由(总体)
const router = new Router();
// 路由设计 RESTful api 请求中间件

// 1. 管理员资源管理路由
router.use('/admin', require('./router/admin'));
// 2. 前端请求接口路由
router.use('/api', require('./router/api'));
// 3. 用户浏览路由
router.use('/', require('./router/www'));

// 自定义的文件类型静态资源托管以及缓存时间
static(router);


server.use(router.routes());

